package viewcontrollers;

import pojos.Expenses;
import viewcontrollers.util.JsfUtil;
import viewcontrollers.util.PaginationHelper;
import beans.ExpensesFacade;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import pojos.Employees;
import util.CurrentTimeToGMT;
import util.ExpensesExcelFile;
import util.SendMail;
import viewcontrollers.util.XMLParser;

@ManagedBean(name = "expensesController")
@SessionScoped
public class ExpensesController implements Serializable {

    /*
     * Varaiables Declarations
     */
    private Expenses current;
    private DataModel items = null;
    private DataModel searchItems = null;
    private DataModel userItems = null;
    private Date fromDate;
    private Date toDate;
    @EJB
    private beans.ExpensesFacade ejbFacade;
    private PaginationHelper pagination;
    private PaginationHelper expensesPagination;
    private PaginationHelper userPagination;
    private int selectedItemIndex;
    private boolean selectedCHB;
    private List expensesTypes;
    private String gmtTime;
    private Employees userMail;
    private Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
    /*
     * End of Varaiables Declarations
     */

    /*
     * Setter and Getter
     */
    public Map<Long, Boolean> getChecked() {
        return checked;
    }

    public void setChecked(Map<Long, Boolean> checked) {
        this.checked = checked;
    }

    public String getGmtTime() {
        return gmtTime;
    }

    public void setGmtTime(String gmtTime) {
        this.gmtTime = gmtTime;
    }

    public List getExpensesTypes() {
        return expensesTypes;
    }

    public void setExpensesTypes(List expensesTypes) {
        this.expensesTypes = expensesTypes;
    }

    public boolean isSelectedCHB() {
        return selectedCHB;
    }

    public void setSelectedCHB(boolean selectedCHB) {
        this.selectedCHB = selectedCHB;
    }

    public Date getFromDate() {
        return fromDate;
    }

    public void setFromDate(Date fromDate) {
        this.fromDate = fromDate;
    }

    public Date getToDate() {
        return toDate;
    }

    public void setToDate(Date toDate) {
        this.toDate = toDate;
    }

    public Employees getUserMail() {
        return userMail;
    }

    public void setUserMail(Employees userMail) {
        this.userMail = userMail;
    }

    /*
     * End of Setter and Getter
     */
    /*
     * Constructor
     */
    public ExpensesController() {
        String is = this.getClass().getClassLoader().getResource("expenseTypes.xml").getPath();
        XMLParser parser = new XMLParser();
        parser.parseTypes(is);

        List<String> expensesTypes = parser.getExpenses();
        this.setExpensesTypes(expensesTypes);
    }

    /*
     * End of Constructor
     */
    /*
     * Business Logic
     */
    public Expenses getSelected() {
        if (current == null) {
            current = new Expenses();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ExpensesFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        if (userType.equalsIgnoreCase("admin")) {
            return "List";
        } else {
            return "userList";
        }

    }

    public String prepareView() {
        current = (Expenses) getItems().getRowData();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        if (userType.equalsIgnoreCase("admin")) {
            selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        } else {
            selectedItemIndex = userPagination.getPageFirstItem() + getItems().getRowIndex();
        }
        return "View";
    }

    public String prepareCreate() {
        current = new Expenses();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            current.setExpenseTotal(current.getExpenseAmount() * current.getUnits());

            CurrentTimeToGMT gmtTime = new CurrentTimeToGMT();
            current.setCreatedAt(gmtTime.getGMT());

            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            String userMail = (String) session.getValue("userName");
            String userType = (String) session.getValue("type");
            Employees employee = getFacade().searchEmployee(userMail);
            this.setUserMail(employee);
            current.setCreatedBy(this.getUserMail());
            if (userType.equalsIgnoreCase("user")) {
                current.setEmployee(this.getUserMail());
            }
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String createAndList() {
        try {
            current.setExpenseTotal(current.getExpenseAmount() * current.getUnits());

            CurrentTimeToGMT gmtTime = new CurrentTimeToGMT();
            current.setCreatedAt(gmtTime.getGMT());

            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            String userMail = (String) session.getValue("userName");
            Employees employee = getFacade().searchEmployee(userMail);
            this.setUserMail(employee);
            current.setCreatedBy(this.getUserMail());
            String userType = (String) session.getValue("type");
            if (userType.equalsIgnoreCase("user")) {
                current.setEmployee(this.getUserMail());
            }
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesCreated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Expenses) getItems().getRowData();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        if (userType.equalsIgnoreCase("admin")) {
            selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        } else {
            selectedItemIndex = userPagination.getPageFirstItem() + getItems().getRowIndex();
        }
        return "Edit";
    }

    public String update() {
        try {
            current.setExpenseTotal(current.getExpenseAmount() * current.getUnits());

            CurrentTimeToGMT gmtTime = new CurrentTimeToGMT();
            current.setCreatedAt(gmtTime.getGMT());

            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            String userMail = (String) session.getValue("userName");
            String userType = (String) session.getValue("type");
            Employees employee = getFacade().searchEmployee(userMail);

            this.setUserMail(employee);
            if (userType.equalsIgnoreCase("user")) {
                current.setEmployee(this.getUserMail());
            }
            current.setCreatedBy(this.getUserMail());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Expenses) getItems().getRowData();

        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        if (userType.equalsIgnoreCase("admin")) {
            selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        } else {
            selectedItemIndex = userPagination.getPageFirstItem() + getItems().getRowIndex();
        }
        performDestroy();
        recreateModel();
        if (userType.equalsIgnoreCase("admin")) {
            return "List";
        } else {
            return "userList";
        }
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            String userType = (String) session.getValue("type");
            if (userType.equalsIgnoreCase("admin")) {
                return "List";
            } else {
                return "userList";
            }
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
        searchItems=null;
        userItems=null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        if (userType.equalsIgnoreCase("admin")) {
            return "List";
        } else {
            return "userList";
        }
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        if (userType.equalsIgnoreCase("admin")) {
            return "List";
        } else {
            return "userList";
        }
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Expenses.class)
    public static class ExpensesControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ExpensesController controller = (ExpensesController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "expensesController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Expenses) {
                Expenses o = (Expenses) object;
                return getStringKey(o.getExpId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ExpensesController.class.getName());
            }
        }
    }

    public String getExpenses() {
        return "expensesresult";
    }

    public PaginationHelper getExpensesPagination() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String businessMail = (String) session.getValue("userName");
        String userType = (String) session.getValue("type");
        final Employees employee = getFacade().searchEmployee(businessMail);
        System.out.println("################Business Mail: " + businessMail);
        System.out.println("################Type: " + userType);
        System.out.println("################Employee ID: " + employee.getEmpId());
        if (userType.equalsIgnoreCase("admin")) {
            if (expensesPagination == null) {
                expensesPagination = new PaginationHelper(10) {

                    @Override
                    public int getItemsCount() {
                        return getFacade().count();
                    }

                    @Override
                    public DataModel createPageDataModel() {
                        return new ListDataModel(getFacade().getExpenses(getFromDate(), getToDate()));
                    }
                };
            }
        } else {
            if (expensesPagination == null) {
                expensesPagination = new PaginationHelper(10) {

                    @Override
                    public int getItemsCount() {
                        return getFacade().count();
                    }

                    @Override
                    public DataModel createPageDataModel() {
                        return new ListDataModel(getFacade().getUserExpenses(getFromDate(), getToDate(), employee));
                    }
                };
            }
        }
        return expensesPagination;
    }

    public DataModel getSearchItems() {
        searchItems = null;
        if (searchItems == null) {
            searchItems = getExpensesPagination().createPageDataModel();
            items = searchItems;
        }
        return items;
    }

    /**
     * get User Pagination Data Model
     * @return 
     */
    public PaginationHelper getUserPagination() {
        if (userPagination == null) {
            userPagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
                    String userMail = (String) session.getValue("userName");
                    Employees employee = getFacade().searchEmployee(userMail);
                    return new ListDataModel(getFacade().getUserExpenses(employee));
                }
            };
        }
        return userPagination;
    }

    public DataModel getUserItems() {
        userItems = null;
        if (userItems == null) {
            userItems = getUserPagination().createPageDataModel();
            items = userItems;
        }
        return items;
    }

    /**
     * Delete Selected Expenses from
     * the Database...
     * @return String represents the Returned Page Name
     */
    public String deleteSelected() {
        try {
            List<Expenses> checkedExpenses = new ArrayList<Expenses>();
            Iterator<Expenses> itr = items.iterator();
            while (itr.hasNext()) {
                Expenses expense = itr.next();
                if (checked.get(expense.getExpId())) {
                    if (!expense.getStatus().equalsIgnoreCase("submitted")) {
                        checkedExpenses.add(expense);
                    } else {
                        JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("DeleteError"));
                        return null;
                    }
                }
            }
            getFacade().deleteExpense(checkedExpenses);
            checked.clear();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesDeleted"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("DeleteError"));
            return null;
        }
    }

    /**
     * Save Selected Expenses
     * Change Selected Expense Status
     * from initial to be Saved
     * @return String represents the Returned Page Name
     */
    public String saveSelected() {
        try {
            List<Expenses> checkedExpenses = new ArrayList<Expenses>();
            Iterator<Expenses> itr = items.iterator();
            while (itr.hasNext()) {
                Expenses expense = itr.next();
                if (checked.get(expense.getExpId())) {
                    expense.setStatus("saved");
                    checkedExpenses.add(expense);
                    getFacade().edit(expense);
                }
            }
            checked.clear();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesSaved"));
            return "List";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("SaveError"));
            return "List";
        }
    }

    /**
     * Submit Selected Expenses
     * Change Status to be Submitted and 
     * generate File with Submitted Expenses and attach it 
     * to mail and sends it to Specific Mail...
     * @return String represents returned Page Name
     */
    public String submitSelected() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userType = (String) session.getValue("type");
        try {
            List<Expenses> checkedExpenses = new ArrayList<Expenses>();
            Iterator<Expenses> itr = items.iterator();
            while (itr.hasNext()) {
                Expenses expense = itr.next();
                if (checked.get(expense.getExpId())) {
                    if (expense.getStatus().equalsIgnoreCase("submitted")) {
                        JsfUtil.addErrorMessage("There are Some Expenses Submitted Before, So They can not be Submitted Again.");
                        recreateModel();
                        if (userType.equalsIgnoreCase("admin")) {
                            return "List";
                        } else {
                            return "userList";
                        }
                    }else{
                        expense.setStatus("submitted");
                        getFacade().edit(expense);
                        checkedExpenses.add(expense);
                    }
                }
            }
            String userName = session.getAttribute("userName").toString();
            String userPass = session.getAttribute("password").toString();
            String fileName = "Expenses_" + userName + "_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";

            String filePath = new ExpensesExcelFile().generateExcelFile(fileName, checkedExpenses);

            SendMail sm = new SendMail();
            sm.sendMailWithAttachFile(fileName, userName, filePath, userPass);

            checked.clear();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpensesSubmitted"));
            recreateModel();
            if (userType.equalsIgnoreCase("admin")) {
                return "List";
            } else {
                return "userList";
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("SubmitError"));
            recreateModel();
            if (userType.equalsIgnoreCase("admin")) {
                return "List";
            } else {
                return "userList";
            }
        }
    }

    /**
     * retrieve regular User Expenses 
     * @return 
     */
    public String listUserExpenses() {
        return "/expenses/userList";
    }
    /*
     * End of Business Logic
     */
}